package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Controller
public class SendMessageTx {

    @Autowired
    private IMessageServcie messageServiceImpl;

    @RequestMapping("/sendMoreMsgTx")
    @ResponseBody
    public String sendMoreMsgTx(){
        // 整个线程池，就跟找一帮人干活儿一样
        int threadCount = 5; // 设定咱要找几个人（线程数）
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);

        try {
            // 让这几个人开始干活儿
            for (int i = 0; i < 10; i++) {
                int messageIndex = i; // 每条消息滴编号
                executorService.submit(() -> { // 提交任务
                    String msg = "msg" + messageIndex; // 整个消息内容
                    System.out.println("发送消息：" + msg); // 打印消息
                    messageServiceImpl.sendMessage("directExchangeTx", "directQueueTxRoutingKey", msg); // 调用发送服务
                });

            }
        } catch (Exception e) {
            e.printStackTrace();
            Thread.currentThread().interrupt(); // 遇到意外赶紧收拾，别卡住
        } finally {
            // 活儿干完了，咱得把人好好安排回去（关掉线程池）
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }

        return "send ok";
    }
}